<template>
    <div ref="chartRef" style="width: 600px; height: 400px"></div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import * as echarts from "echarts";

const chartRef = ref<HTMLDivElement | null>(null);
let chart: echarts.ECharts | null = null;
let timerId: number | null = null;

// 示例数据，真实使用可通过props传入或接口请求
const khpmY = ["客户A", "客户B", "客户C", "客户D", "客户E", "客户F", "客户G", "客户H"];
const khpmD = [120, 200, 150, 80, 70, 110, 130, 90];

const viewSize = 4;
let startIndex = khpmY.length;

function updateChartView(start: number, viewSize: number) {
    const safeStart = Math.max(start, viewSize);
    const viewY = khpmY.slice(safeStart - viewSize, safeStart);
    const viewD = khpmD.slice(safeStart - viewSize, safeStart);

    const option: echarts.EChartsOption = {
        tooltip: {
            trigger: "axis",
            axisPointer: { type: "shadow" },
        },
        grid: {
            left: "3%",
            right: "8%",
            bottom: "3%",
            top: "3%",
            containLabel: true,
        },
        xAxis: {
            type: "value",
            axisLine: { show: false, lineStyle: { color: "#DDDDDD" } },
            splitLine: {
                show: true,
                lineStyle: { type: "dashed", color: "#DDDDDD" },
            },
        },
        yAxis: {
            type: "category",
            data: viewY,
            axisTick: { show: false },
            axisLine: { lineStyle: { color: "#DDDDDD" } },
        },
        legend: { show: false },
        series: [
            {
                type: "bar",
                data: viewD,
                barWidth: 16,
                itemStyle: {
                    borderRadius: [0, 8, 8, 0],
                    color: new echarts.graphic.LinearGradient(0, 0, 1, 1, [
                        { offset: 0, color: "#DDDDDD" },
                        { offset: 1, color: "#43A8F4" },
                    ]),
                },
            },
        ],
    };
    // ECharts 的 setOption 默认会做一次 平滑的图表重绘动画，这就是滚动时看起来平滑切换的原因。
    chart?.setOption(option);
}

function startScroll() {
    if (!chart && chartRef.value) {
        chart = echarts.init(chartRef.value);
    }

    updateChartView(startIndex, viewSize);

    timerId = window.setInterval(() => {
        startIndex--;
        if (startIndex < viewSize) {
            startIndex = khpmY.length;
        }
        updateChartView(startIndex, viewSize);
    }, 2000);
}

onMounted(() => {
    startScroll();
});

onBeforeUnmount(() => {
    if (timerId !== null) {
        clearInterval(timerId);
    }
    chart?.dispose();
});
</script>

<style scoped>
/* 可以根据需求自行调整样式 */
</style>
